package com.itheima.interceptor;

import com.aliyuncs.utils.StringUtils;
import com.itheima.utils.JwtUtils;
import io.jsonwebtoken.Claims;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
@Component
public class TokenInterceptor implements HandlerInterceptor {
    private static final Logger log = LoggerFactory.getLogger(TokenInterceptor.class);

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //1.判断是否是登录请求
        //1.1获取请求的url
        String path = request.getRequestURI();
        //1.2判断url是否是登录请求.是否以login结尾，是则放行，无效则拒绝401
       if (path.endsWith("login")){
           return true;
       }
        //2.如果不是登录请求，则校验 token是否有效
        //2.1获取token
        String token = request.getHeader("token");
        //2.2判断token是否为空,有值则校验
        if(!StringUtils.isEmpty(token)){
            //2.3校验token
            try {
                Claims claims = JwtUtils.parseJWT(token);
                log.info("解析的token是{}",claims);
                return true;
            } catch (Exception e) {
                log.error("解析token失败了", e);
            }
        }

        //2.4如果不报错，解析token，放行
        //return true则放行，return false则不放行
        response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
        return false;
    }
}
